package com.mall.product.api.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.listener.PageReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import com.mall.common.util.JsonResult;
import com.mall.model.*;
import com.mall.product.api.dao.ProductBundleItemMapper;
import com.mall.product.api.dao.ProductBundleMapper;
import com.mall.product.api.dao.ProductMapper;
import com.mall.service.ProductService;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/*
* 商品业务实现类*/
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    ProductMapper productMapper;

    @Autowired
    ProductBundleMapper productBundleMapper;

    @Autowired
    ProductBundleItemMapper productBundleItemMapper;

    @Override
    public Long create(Product product) {
       /*基本数据校验*/
        if(!StringUtils.hasText(product.getName())) {
            throw new IllegalArgumentException("name不能为空");
        }
        if(product.getBrandId() == null) {
            throw new IllegalArgumentException("brandId不能为空");
        }
        if(product.getCategoryId() == null) {
            throw new IllegalArgumentException("categoryId不能为空");
        }
        if(product.getPrice() == null) {
            throw  new IllegalArgumentException("price不能为空");
        }

        //加上基础默认值
        if(product.getStatus() == null) product.setStatus(1);
        if(product.getIsHot() == null) product.setIsHot(0);
        if(product.getIsDel() == null) product.setIsDel(0);
        if(product.getStock() == null) product.setStock(0);
        if(product.getSalesCount() == null) product.setSalesCount(0);

        //插入
        productMapper.insert(product);
        return product.getId();


    }

    @Override
    public boolean updateById(Product product) {
        if(product.getId() == null) {
            throw new IllegalArgumentException("id不能为空");
        }
        return productMapper.updateById(product) > 0;
    }

    @Override
    public Product getById(Long id) {
        Product p = productMapper.selectById(id);
        if (p == null) {return null;}
        return (p.getIsDel() == 0)? p : null;
    }

    @Override
    public List<Product> pageQuery(String keyword, Long brandId, Long categoryId, Integer status, Integer isHot, int page, int size) {
        //兜底值
       int safePage = page < 1 ? 1 : page;
       int safeSize = (size < 1 || size > 100) ? 10 : size;
       int offset = (safePage - 1) * safeSize;

       //条件判断
        LambdaQueryWrapper<Product> qw = new LambdaQueryWrapper<>();
        qw.eq(brandId != null,Product::getBrandId,brandId);
        qw.eq(categoryId != null,Product::getCategoryId,categoryId);
        qw.eq(status != null,Product::getStatus,status);
        qw.eq(isHot != null,Product::getIsHot,isHot);
        qw.eq(Product::getIsDel,0);
          if(StringUtils.hasText(keyword)) {
              qw.and(w -> w.like(Product::getName,keyword)
                      .or().like(Product::getSummary,keyword));
          }
          //排序加分页
          qw.orderByDesc(Product::getId);
          qw.last("LIMIT " + safeSize + " OFFSET " + offset);

          return productMapper.selectList(qw);

    }

    @Override
    public long count(String keyword, Long brandId, Long categoryId, Integer status, Integer isHot) {
        LambdaQueryWrapper<Product> qw = new LambdaQueryWrapper<>();
        qw.eq(brandId != null, Product::getBrandId, brandId);
        qw.eq(categoryId != null, Product::getCategoryId, categoryId);
        qw.eq(status != null, Product::getStatus, status);
        qw.eq(isHot != null, Product::getIsHot, isHot);
        qw.eq(Product::getIsDel, 0);
        if (StringUtils.hasText(keyword)) {
            qw.and(w -> w.like(Product::getName, keyword)
                    .or().like(Product::getSummary, keyword));
        }
        return productMapper.selectCount(qw);
    }

    @Override
    public boolean softDeleted(Long id) {
        //逻辑删除is_del
        Product p = new Product();
        p.setId(id);
        p.setIsHot(1);
        return productMapper.updateById(p) > 0;
    }

    @Override
    public boolean updateStatus(Long id, Integer status) {
        Product p = new Product();
        p.setId(id);
        p.setStatus(status);
        return productMapper.updateById(p) > 0;
    }

    @Override
    public boolean updateisHot(Long id, Integer isHot) {
        Product p = new Product();
        p.setId(id);
        p.setIsHot(isHot);
        return productMapper.updateById(p) > 0;
    }

    @Override
    public boolean updateStock(Long id, Integer stock) {
        Product p = new Product();
        p.setId(id);
        p.setStock(stock);
        return productMapper.updateById(p) > 0;
    }

    @Override
    public boolean jianshaoStock(Long id, Integer jianshaoStock) {
        Product p = productMapper.selectById(id);
        if(p == null) {
            throw new IllegalArgumentException("没有该商品！");
        }
        if(p.getStock() < jianshaoStock) {
            throw new IllegalArgumentException("库存量不足 购买失败！");
        }
        Integer newStock = p.getStock() - jianshaoStock;

        Product updateProduct = new Product();
        updateProduct.setId(id);
        updateProduct.setStock(newStock);
        return productMapper.updateById(updateProduct) > 0;
    }

    @Override
    public boolean restorejianshaoStock(Long id, Integer jianshaoStock) {
       Product p = productMapper.selectById(id);
       if(p == null) {
           throw new IllegalArgumentException("没有该商品");
       }

       Integer newstock = p.getStock() + jianshaoStock;

       Product update = new Product();
       update.setId(id);
       update.setStock(newstock);

       return productMapper.updateById(update) > 0;
    }


    @Override
    public boolean updatePrice(Long id, BigDecimal price) {
        Product p = new Product();
        p.setId(id);
        p.setPrice(price);
        return productMapper.updateById(p) > 0;
    }

    @Override
    public List<Product> getByBrandId(Long brandId, Integer status) {
       LambdaQueryWrapper<Product> qw = new LambdaQueryWrapper<>();
       qw.eq(Product::getBrandId,brandId);
       qw.eq(status != null,Product::getStatus,status);
       qw.orderByDesc(Product::getId);

       return productMapper.selectList(qw);
    }

    @Override
    public List<Product> getByCategoryId(Long categoryId, Integer status) {
        LambdaQueryWrapper<Product> qw = new LambdaQueryWrapper<>();
        qw.eq(Product::getCategoryId, categoryId);
        qw.eq(status != null, Product::getStatus, status);
        qw.eq(Product::getIsDel, 0);
        qw.orderByDesc(Product::getId);
        return productMapper.selectList(qw);
    }

    @Override
    public ProductBack getKeyMetrics(LocalDate startDate, LocalDate endDate) {
        //获取总商品数量
        BigDecimal totalProducts = productMapper.getTotalProductsCount(startDate, endDate);

        //获取上架商品数
        BigDecimal onsaleProducts = productMapper.getOnsalesProductsCount(startDate, endDate);

        //获取库存小于500的数量
        BigDecimal lowStockProducts = productMapper.getLowStockProductsCount(startDate, endDate);

        return new ProductBack(totalProducts, onsaleProducts, lowStockProducts);
    }

    @Override
    public List<Map<String, Object>> getProductcount(LocalDate startDate, LocalDate endDate) {
        // 获取所有分类的商品统计
        return productMapper.getAllCategoryProductCount(startDate, endDate);
    }

    @Override
    public List<Map<String, Object>> getStockBack(LocalDate startDate, LocalDate endDate) {
        List<Map<String, Object>> stockList = new ArrayList<>();

        // 库存区间：0-100, 101-300, 301-500, 501-1000, 1000+
        int[][] ranges = {{0, 100}, {101, 300}, {301, 500}, {501, 1000}, {1001, 999999}};

        BigDecimal totalProducts = productMapper.getTotalProductsCount(startDate, endDate);

        for (int[] range : ranges) {
            Map<String, Object> stockInfo = new HashMap<>();
            BigDecimal productCount = productMapper.getStockRangeProductCount(range[0], range[1], startDate, endDate);

            stockInfo.put("range", range[0] + "-" + (range[1] == 999999 ? "∞" : range[1]));
            stockInfo.put("productCount", productCount);

            // 计算百分比
            BigDecimal percentage = BigDecimal.ZERO;
            if (totalProducts.compareTo(BigDecimal.ZERO) > 0) {
                percentage = productCount.divide(totalProducts, 4, BigDecimal.ROUND_HALF_UP)
                        .multiply(new BigDecimal("100"));
            }
            stockInfo.put("percentage", percentage);

            stockList.add(stockInfo);
        }

        return stockList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<String> batchUpdateStatus(List<Long> productIds, Integer status) {
        try{
            //参数验证
            if(productIds == null || productIds.isEmpty()) {
                throw new IllegalArgumentException("商品不能为空");
            }

            if(status == null || (status != 0 && status != 1)) {
                throw new IllegalArgumentException("无效的状态值 只能是0或者1");
            }

            //将List转换成为逗号分隔的字符串
            String productIdsStr = productIds.stream().map(String::valueOf).collect(Collectors.joining(","));

            //执行批量更新
            int count = productMapper.batchUpdateStatus(productIdsStr,status);

            String statusText = status == 1? "上架":"下架";

            return JsonResult.success("批量" + statusText + "成功，共更新 " + count + " 个商品");

        } catch (Exception e) {

            return (JsonResult<String>) JsonResult.fail("批量更新状态失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<String> batchUpdateHot(List<Long> productIds, Integer isHot) {
        try{
            if(productIds == null || productIds.isEmpty()) {
                throw new IllegalArgumentException("商品列表不能为空");
            }
            if(isHot == null || (isHot != 1 && isHot != 0)) {
                throw new IllegalArgumentException("不合法的状态值");
            }

            String productIdstr = productIds.stream().map(String::valueOf).collect(Collectors.joining(","));
            int count = productMapper.batchUpdateHot(productIdstr,isHot);

            String hotText = isHot == 1 ? "设为热门" : "取消热门";

            return JsonResult.success("批量" + hotText + "成功共" + count + "商品");

        } catch (Exception e) {
            return (JsonResult<String>) JsonResult.fail("批量更新热门状态失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<String> batchDelete(List<Long> productIds) {
        try {
            if(productIds == null || productIds.isEmpty()) {
                throw new IllegalArgumentException("商品列表不能为空");
            }
            String productIdsStr = productIds.stream()
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));

            int count =  productMapper.batchDelete(productIdsStr);

            return JsonResult.success("批量删除成功，共删除 " + count + " 个商品");

        } catch (Exception e) {
            return (JsonResult<String>) JsonResult.fail("批量删除失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<String> batchUpdateStock(List<Long> productIds, String operationType, Integer amount) {
        try {
            if (productIds == null || productIds.isEmpty()) {
                throw new IllegalArgumentException("商品列表不能为空");
            }
            if (amount == null || (amount <= 0)) {
                throw new IllegalArgumentException("无效的操作值");
            }

            String productIdsStr = productIds.stream()
                    .map(String::valueOf)
                    .collect(Collectors.joining(","));
            int count = 0;
            switch (operationType) {
                case "deduct":
                    count = productMapper.batchDeductStock(productIdsStr, amount);
                    break;
                case "restore":
                    count = productMapper.batchRestoreStock(productIdsStr, amount);
                    break;
                case "set":
                    count = productMapper.batchSetStock(productIdsStr, amount);
                    break;
                default:
                    return (JsonResult<String>) JsonResult.fail("不支持的操作类型");
            }

            return JsonResult.success("批量成功，共操作 " + count + " 个商品");

        } catch (Exception e) {
            throw new IllegalArgumentException("批量库存操作失败");
        }

    }


    //============导出导出相关方法实现

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void exportProducts(HttpServletResponse response, String keyword, Long brandId, Long categoryId, Integer status, Integer isHot) {
        try{
            ProductQuery query  = new ProductQuery();
            query.setKeyword(keyword);
            query.setBrandId(brandId);
            query.setCategoryId(categoryId);
            query.setStatus(status);
            query.setIsHot(isHot);
            List<Product> products = productMapper.selectByQuery(query);

            //设置响应头
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-Disposition", "attachment; filename=products.xlsx");

            //生成Excel文件
            generateExcel(response.getOutputStream(),products);

            System.out.println("导出商品成功，条件: keyword={}, brandId={}, categoryId={}, status={}, isHot={}, 数量: {}" +
                    keyword +brandId +categoryId + status + isHot + products.size());
        } catch (Exception e) {
            throw new IllegalArgumentException("导出失败");
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<String> importProducts(MultipartFile file) {
        try {
            if (file == null || file.isEmpty()) {
                return (JsonResult<String>) JsonResult.fail("请选择要导入的文件");
            }

            String fileName = file.getOriginalFilename();
            if (!isValidFileType(fileName)) {

                return (JsonResult<String>) JsonResult.fail("不支持的文件类型，请上传Excel或CSV文件");
            }

            if (file.getSize() > 10 * 1024 * 1024) {

                return (JsonResult<String>) JsonResult.fail("文件大小不能超过10MB");
            }

            int count = processImportFile(file);


            return JsonResult.success("导入成功，共导入 " + count + " 个商品");

        } catch (Exception e) {

            return (JsonResult<String>) JsonResult.fail("导入失败：" + e.getMessage());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void downloadTemplate(HttpServletResponse response) {
        try {
            // 设置响应编码
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/csv; charset=UTF-8");
            
            // 使用英文文件名避免编码问题
            String filename = "product_import_template.csv";
            response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
            
            // 禁用缓存
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");

            generateTemplate(response.getOutputStream());

            System.out.println("下载导入模板成功");

        } catch (Exception e) {
            System.out.println("下载导入模板失败");
            throw new RuntimeException("下载模板失败：" + e.getMessage());
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<String> cloneProduct(Long productId, CloneRequest request) {
       try {
           if( productId == null) {
               System.out.println("商品为空 克隆失败");
               return (JsonResult<String>) JsonResult.fail("商品id不能为空");
           }
           if( request.getCount() == null || request.getCount() <= 0 || request.getCount() > 10) {
               System.out.println("克隆量非法");
               return (JsonResult<String>) JsonResult.fail("克隆数量必须1-10");
           }
           Product originalProduct = productMapper.selectById(productId);
           if (originalProduct == null) {
               System.out.println("原商品不存在");
               return (JsonResult<String>) JsonResult.fail("原商品不存在");
           }

           int count = processProductClone(originalProduct,request);
           System.out.println("商品"+productId+"克隆成功");
           return JsonResult.success("克隆成功 一共克隆" + count + "个产品");
       } catch (Exception e) {
           throw new IllegalArgumentException("克隆失败");
       }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public JsonResult<String> createBundle(ProductBundleRequest request) {
        try {
            if(request.getName() == null || request.getName().trim().isEmpty()) {
                System.out.println("创建组合失败 组合名称不能为空");
                return (JsonResult<String>) JsonResult.fail("组合名称不能为空");
            }
            if (request.getSelectedProducts() == null || request.getSelectedProducts().isEmpty()) {
                System.out.println("创建商品组合失败：未选择商品");
                return (JsonResult<String>) JsonResult.fail("请选择要组合的商品");
            }

            if(request.getPrice() == null || request.getPrice().compareTo(BigDecimal.ZERO) < 0 ) {
                System.out.println("无效的价格");
                return (JsonResult<String>) JsonResult.fail("价格不能为负数");
            }

            Long bundleId = processProductBundle(request);
            System.out.println("创建商品组合成功，名称: {}, 商品数量: {}, 组合ID: {}" +
                    request.getName() + request.getSelectedProducts().size() + bundleId);

            return JsonResult.success("商品组合创建成功，ID: " + bundleId);
        } catch (Exception e) {
            throw new IllegalArgumentException("创建失败");
        }
    }
    /**
     * 获取操作类型的中文描述
     */
    private String getOperationText(String operationType) {
        switch (operationType) {
            case "deduct": return "减少库存";
            case "restore": return "恢复库存";
            case "set": return "设置库存";
            default: return "库存操作";
        }
    }

    /**
     * 验证文件类型是否支持
     */
    private boolean isValidFileType(String fileName) {
        if (fileName == null) return false;
        String lowerFileName = fileName.toLowerCase();
        return lowerFileName.endsWith(".xlsx") || lowerFileName.endsWith(".xls") || lowerFileName.endsWith(".csv");
    }

    /**
     * 处理导入文件
     */
    private int processImportFile(MultipartFile file) throws Exception {
       try {
           List<Product> products = new ArrayList<>();

           //使用EasyExcel读取文件
           EasyExcel.read(file.getInputStream(), new PageReadListener<ProductImportData>(dataList -> {
               for (ProductImportData importData : dataList) {
                   try{
                       //验证必填字段
                       if(StringUtils.isEmpty(importData.getName())) {
                           System.out.println("跳过无效字段 商品名称为空");
                           continue;
                       }
                       if (importData.getBrandId() == null) {
                           System.out.println("跳过无效数据：品牌ID为空，商品名称：{}" + importData.getName());
                           continue;
                       }
                       if (importData.getCategoryId() == null) {
                           System.out.println("跳过无效数据：分类ID为空，商品名称：{}" + importData.getName());
                           continue;
                       }
                       if (importData.getPrice() == null || importData.getPrice().compareTo(BigDecimal.ZERO) <= 0) {
                           System.out.println("跳过无效数据：价格无效，商品名称：{}" + importData.getName());
                           continue;
                       }
                       if (importData.getStock() == null || importData.getStock() < 0) {
                           System.out.println("跳过无效数据：库存无效，商品名称：{}" + importData.getName());
                           continue;
                       }

                       //转换为Product对象
                       Product product = new Product();
                       product.setName(importData.getName());
                       product.setBrandId(importData.getBrandId());
                       product.setCategoryId(importData.getCategoryId());
                       product.setSummary(importData.getSummary());
                       product.setPrice(importData.getPrice());
                       product.setMarketPrice(importData.getMarketPrice());
                       product.setStock(importData.getStock());
                       product.setMainPicUrl(importData.getMainPicUrl());
                       product.setPicUrls(importData.getPicUrls());
                       product.setStatus(importData.getStatus() != null ? importData.getStatus() : 1);
                       product.setIsHot(importData.getIsHot() != null ? importData.getIsHot() : 0);
                       product.setDescription(importData.getDescription());
                       product.setSalesCount(0);
                       product.setIsDel(0);
                       product.setCreatedTime(LocalDateTime.now());
                       product.setUpdateTime(LocalDateTime.now());

                       products.add(product);
                   } catch (Exception e) {
                       System.out.println("跳过无效数据");
                   }
               }
           })).sheet().doRead();
           //批量保存商品
           if(!products.isEmpty()) {
               for(Product product : products) {
                   productMapper.insert(product);
               }
           }
           return products.size();
       } catch (Exception e) {
           throw new RuntimeException("处理导入文件失败：" + e.getMessage());
       }
       //批量保存 商品

    }

    /**
     * 生成Excel文件
     */
    private void generateExcel(java.io.OutputStream outputStream, List<Product> products) throws Exception {
      try {
          //定义excel表头
          List<List<String>> head = new ArrayList<>();
          head.add(Arrays.asList("商品id"));
          head.add(Arrays.asList("商品名称"));
          head.add(Arrays.asList("品牌id"));
          head.add(Arrays.asList("分类id"));
          head.add(Arrays.asList("商品简介"));
          head.add(Arrays.asList("销售价格"));
          head.add(Arrays.asList("市场价"));
          head.add(Arrays.asList("库存"));
          head.add(Arrays.asList("主图地址"));
          head.add(Arrays.asList("图片地址列表"));
          head.add(Arrays.asList("状态"));
          head.add(Arrays.asList("是否热门"));
          head.add(Arrays.asList("商品描述"));
          head.add(Arrays.asList("销量"));
          head.add(Arrays.asList("创建时间"));
          head.add(Arrays.asList("更新时间"));

          //准备数据
          List<List<Object>> data = new ArrayList<>();
          for(Product product : products) {
              List<Object> row = new ArrayList<>();
              row.add(product.getId());
              row.add(product.getName());
              row.add(product.getBrandId());
              row.add(product.getCategoryId());
              row.add(product.getSummary());
              row.add(product.getPrice());
              row.add(product.getMarketPrice());
              row.add(product.getStock());
              row.add(product.getMainPicUrl());
              row.add(product.getPicUrls());
              row.add(product.getStatus() == 1 ? "上架" : "下架");
              row.add(product.getIsHot() == 1 ? "是" : "否");
              row.add(product.getDescription());
              row.add(product.getSalesCount());
              row.add(product.getCreatedTime());
              row.add(product.getUpdateTime());
              data.add(row);

          }

          //使用Excel生成文件
          EasyExcel.write(outputStream)
                  .head(head)
                  .sheet("商品列表")
                  .doWrite(data);
      } catch (Exception e) {
          throw new IllegalArgumentException("生成excel文件失败");
      }
    }

    /**
     * 生成导入模板
     */
    private void generateTemplate(java.io.OutputStream outputStream) throws Exception {
        try {
            // 使用CSV格式替代Excel，避免AWT依赖问题
            String csvContent = generateCSVTemplate();
            
            // 添加调试日志
            System.out.println("生成的CSV内容长度: " + csvContent.length());
            System.out.println("生成的CSV内容前100字符: " + csvContent.substring(0, Math.min(100, csvContent.length())));
            
            // 使用字节数组写入，避免编码问题
            byte[] bytes = csvContent.getBytes("UTF-8");
            System.out.println("字节数组长度: " + bytes.length);
            
            outputStream.write(bytes);
            outputStream.flush();
            
            System.out.println("CSV内容写入完成");
            
        } catch (Exception e) {
            System.err.println("生成导入模板失败: " + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("生成导入模板失败" + e.getMessage());
        }
    }
    
    /**
     * 生成CSV格式的导入模板
     */
    private String generateCSVTemplate() {
        StringBuilder csv = new StringBuilder();
        
        // 添加BOM，确保Excel正确识别UTF-8编码
        csv.append("\uFEFF");
        
        // 使用英文表头避免编码问题
        csv.append("Product Name*,Brand ID*,Category ID*,Summary,Sales Price*,Market Price,Stock*,Main Image URL,Image URLs,Status,Is Hot,Description\n");
        
        // 添加示例数据（英文）
        csv.append("Sample Product,1,1,This is a sample product,99.99,129.99,100,http://example.com/image1.jpg,http://example.com/image1.jpg,http://example.com/image2.jpg,1,0,Detailed product description\n");
        
        return csv.toString();
    }

    /**
     * 处理商品克隆
     */
    private int processProductClone(Product originalProduct, CloneRequest request) throws Exception {
        try{
            int successCount = 0;
            for (int i = 1; i <= request.getCount(); i++) {
                try {
                    //创建新商品对象
                    Product newProduct = new Product();

                    //复制基本信息
                    newProduct.setBrandId(originalProduct.getBrandId());
                    newProduct.setCategoryId(originalProduct.getCategoryId());
                    newProduct.setSummary(originalProduct.getSummary());
                    newProduct.setPrice(originalProduct.getPrice());
                    newProduct.setMarketPrice(originalProduct.getMarketPrice());
                    newProduct.setStock(originalProduct.getStock());
                    newProduct.setMainPicUrl(originalProduct.getMainPicUrl());
                    newProduct.setPicUrls(originalProduct.getPicUrls());
                    newProduct.setStatus(0); // 默认下架
                    newProduct.setIsHot(0); // 默认非热门
                    newProduct.setDescription(originalProduct.getDescription());
                    newProduct.setSalesCount(0);
                    newProduct.setIsDel(0);
                    newProduct.setCreatedTime(LocalDateTime.now());
                    newProduct.setUpdateTime(LocalDateTime.now());

                    // 根据命名规则生成新商品名称
                    String newName = generateCloneName(originalProduct.getName(), request, i);
                    newProduct.setName(newName);

                    // 保存新商品
                    productMapper.insert(newProduct);
                    successCount++;
                    System.out.println("成功克隆" + originalProduct.getName() + newName);
                } catch (Exception e) {
                    System.out.println("克隆商品失败" + i);
                }
            }
            return successCount;
        } catch (Exception e) {
           throw new RuntimeException("处理克隆失败" + e.getMessage());
        }
    }

    /**
     * 处理商品组合创建
     */
    private Long processProductBundle(ProductBundleRequest request) throws Exception {
        try {
            System.out.println("开始处理商品组合创建，请求数据：" + request);

            //验证选中的商品是否存在
            List<Long> productIds = request.getSelectedProducts();
            if (productIds == null || productIds.isEmpty()) {
                throw new IllegalArgumentException("选中的商品列表不能为空");
            }

            System.out.println("验证商品列表，商品ID：" + productIds);

            //检查是否都存在
            for(Long productId : productIds) {
                Product product = productMapper.selectById(productId);
                if(product == null) {
                    throw new IllegalArgumentException("商品" + productId + "不存在");
                }
                if(product.getIsDel() == 1) {
                    throw new IllegalArgumentException("商品ID" + productId + "已被删除");
                }
                System.out.println("商品验证通过：" + product.getName());
            }

            System.out.println("开始创建商品组合...");
            ProductBundle bundle = new ProductBundle();
            bundle.setName(request.getName());
            bundle.setDescription(request.getDescription());
            bundle.setPrice(request.getPrice());
            bundle.setStatus(1); // 默认启用
            bundle.setCreateTime(new Date());
            bundle.setUpdateTime(new Date());

            System.out.println("商品组合对象：" + bundle);

            System.out.println("插入商品组合到数据库...");
            int insertResult = productBundleMapper.insert(bundle);
            System.out.println("插入结果：" + insertResult);

            Long bundleId = bundle.getId();
            System.out.println("获取到的组合ID：" + bundleId);

            if (bundleId == null) {
                throw new RuntimeException("插入商品组合后未获取到ID");
            }

            System.out.println("开始插入商品组合项...");
            for (Long productId : productIds) {
                ProductBundleItem item = new ProductBundleItem();
                item.setBundleId(bundleId);
                item.setProductId(productId);
                item.setQuantity(1); // 默认数量为1
                item.setCreateTime(new Date());

                System.out.println("插入商品组合项：" + item);
                int itemInsertResult = productBundleItemMapper.insert(item);
                System.out.println("商品组合项插入结果：" + itemInsertResult);
            }

            System.out.println("成功创建商品组合：{}，ID：{}，包含商品数量：{}" +
                    request.getName() + bundleId + productIds.size());

            return bundleId;

        } catch (Exception e) {
            System.err.println("处理商品组合创建失败，详细错误：" + e.getMessage());
            e.printStackTrace();
            throw new RuntimeException("处理商品组合创建失败：" + e.getMessage());
        }
    }



    private String generateCloneName(String originalName, CloneRequest request, int index) {
        // 添加空值检查
        if (originalName == null || originalName.trim().isEmpty()) {
            originalName = "未命名商品";
        }

        // 添加参数验证
        if (request == null) {
            return originalName + "_" + index;
        }

        if (index <= 0) {
            index = 1;
        }

        switch (request.getNamingRule()) {
            case "copy":
                return originalName + "_" + index;
            case "variant":
                return originalName + "-变体" + index;
            case "custom":
                String prefix = StringUtils.hasText(request.getCustomPrefix()) ?
                        request.getCustomPrefix() : "克隆";
                return prefix + "_" + index;
            default:
                return originalName + "_" + index;
        }
    }


}
